package com.xj.sever.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xj.mapper.Iuser;
import com.xj.mapper.Iuserr;
import com.xj.pojo.USerr;
import com.xj.pojo.Userrrr;
import com.xj.until.RedisUtils;
import com.xj.config.SendTenXunYunSmsUtil;
import com.xj.mapper.UserMapper;
import com.xj.pojo.User;
import com.xj.sever.UserSever;
import com.xj.until.Result;
import com.xj.until.Useres;
import com.xuecheng.base.utils.PhoneUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class UserSverimpl implements UserSever {

    @Resource
    SendTenXunYunSmsUtil sendTenXunSmsUtil;
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisUtils redisUtils;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    Iuser iuser;

    @Autowired
    Iuserr iuserr;

    @Override
    public Result send(String phone) {
  PhoneUtil phoneUtil = new PhoneUtil();
        //手机号格式校验

        Boolean matches = phoneUtil.isMatches(phone);
        if (matches){
            sendTenXunSmsUtil.send(phone);
            return Result.ok("success");
        }else {
            return Result.error("手机号输入错误");
        }

    }
    @Override
    public Result selectAll(Integer qi,Integer num) {
        if (qi==null||num==null||qi<0||num<0){
            qi=0;
            num=5;
        }
        Object o = redisUtils.get("alluser");
        if(o!=null){
            return Result.ok(o);
        }
        List<User> alluser = userMapper.alluser(qi,num);
        boolean set = redisUtils.set("alluser", alluser, 60 * 2);
        System.out.println(set);
        return Result.ok(alluser);
    }

    @Override
    public Result register(User user) {
        USerr uSerr = new USerr();
        uSerr.setId(0);
        uSerr.setUsername(user.getUsername());
        //去重
        QueryWrapper<USerr> wrapper = new QueryWrapper<>();
        wrapper.eq("username",uSerr.getUsername());
        USerr uSerr1 = iuserr.selectOne(wrapper);
        if(uSerr1!=null){
            return Result.error("用户名已存在");
        }
        //注册
        uSerr.setName(user.getName());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(user.getPassword());
        uSerr.setPassword(encode);
        uSerr.setIdcader(user.getIdcader());
        uSerr.setRoleid(user.getRoleid());
        uSerr.setUnit(user.getUnit());
        int insert = iuserr.insert(uSerr);
        if(insert>0){
            redisTemplate.delete("alluser");
            return Result.ok("注册成功");
        }else {
            return Result.error("注册失败");
        }

    }
    @Override
    public Result delete(String id) {
        User user = new User();
        //可以通过条件自动拼接动态SQL
        user.setId(1);
        user.setIsdelete(0);
        //updateById 参数是一个对象！
        int i = iuser.updateById(user);
        System.out.println(i);
        redisTemplate.delete("alluser");
        return  Result.ok("删除成功");
    }
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public Result reset(Integer id) {
        String randomString = getRandomString(8);
        User user = new User();
        user.setId(id);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(randomString);
        user.setPassword(encode);
        int i = iuser.updateById(user);
        if(i>0){

            String message = "flyingingcheng@163.com";
            Userrrr userrrr = new Userrrr();
            userrrr.setPassword(randomString);
            userrrr.setEmail(message);
            rabbitTemplate.convertAndSend("simple.queue", userrrr);
            redisTemplate.delete("alluser");
            return Result.ok("重置成功");


        }else {
            return Result.error("重置失败");
        }

    }

    @Override
    public Result authority(Integer id, String roleid) {
        User user = new User();
        user.setId(id);
        if (roleid!=null||!roleid.equals("1")||!roleid.equals("2")||!roleid.equals("3")||!roleid.equals("4")) {

            user.setRoleid(roleid);
            int i = iuser.updateById(user);
            if (i > 0) {
                redisTemplate.delete("alluser");
                return Result.ok("权限设置成功");
            }
        }
        return Result.error(500,"权限设置失败");


    }
    @Autowired
    Useres useres;



    @Override
    public Result centSelect() {
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        User user= userMapper.select1(userss.getId());
        user.setPassword("*****************");
        if (user != null) {
            return Result.ok(user);
        }
        return Result.error(500, "查询失败");
    }

    @Override
    public Result updatePassword(String password, String newpassword) {
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        User user= userMapper.select1(userss.getId());
        String oldpassword = user.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        boolean matches = encoder.matches(oldpassword, newpassword);
//        boolean matches1 = encoder.matches(oldpassword, password);

        if (!encoder.matches(oldpassword, password)) {//判断密码输入是否正确
            if (!encoder.matches(oldpassword, newpassword)) {//判断密码是否和之前一样
                User user1=new User();
                user1.setId(user.getId());
                String encode = encoder.encode(newpassword);
                user1.setPassword(encode);
                int i = iuser.updateById(user);
                if (i > 0) {
                    redisTemplate.delete("alluser");
                    return Result.ok("密码修改成功");

                }
            }else return Result.error(500,"输入的密码与之前密码一致");

        }else
            return Result.error(500,"输入的密码与之前密码不一致");

        return Result.error(500,"修改失败");
    }

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @Override
    public Result updateemail() {
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        User user= userMapper.select1(userss.getId());
        String msg =user.getPhone();
        rocketMQTemplate.syncSend("sync", msg);
        return Result.ok("验证码发送成功");
    }

    @Override
    public Result emailcode(String code) {
        if (code==null||code.equals(""))
            return Result.error(500,"验证码不能为空");
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        String s = (String) redisUtils.get(userss.getPhone());
        if (code.equals(s)){
            return Result.ok("验证码正确");
        }else return Result.error(500,"验证码错误");

    }
    @Override
    public Result emali1(String email) {
        if (email==null||email.equals(""))
            return Result.error(500,"输入的邮箱不能为空");
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        User user = new User();
        user.setId(userss.getId());
        user.setEmail(email);
        int i = iuser.updateById(user);
        if (i>0){
            return Result.ok("邮箱修改成功");
        }else
            return Result.error(500,"邮箱修改失败");
    }

    @Override
    public Result sendphone() {
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        String msg = userss.getEmail();
        rocketMQTemplate.asyncSend("async", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("生产者:  异步发送成功");
                log.info("生产者:  异步发送成功");
            }
            @Override
            public void onException(Throwable throwable) {
                System.out.println("生产者:  异步发送失败");
                log.info("生产者:  异步发送失败");
            }
        });
        return Result.ok("邮箱成功");
    }

    @Override
    public Result sendphone1(String code) {
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        String s = (String) redisUtils.get(userss.getEmail());
        if (s.equals(code)){
            return  Result.ok("验证码正确");
        }else
            return Result.error(500,"验证码错误");
    }

    @Override
    public Result phone(String phone) {
        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userss = useres.userss(principal);
        User user = new User();
        user.setId(userss.getId());
        user.setPhone(phone);
        int i = iuser.updateById(user);
        if (i>0){
            return Result.ok("手机号修改成功");
        }else
            return Result.error(500,"手机号修改失败");
    }



    public static String getRandomString(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }


}
